<template>
  <div class="head-container">
    <ns-input v-model="deptName" class="mb-20px" clearable placeholder="请输入数据源名称">
      <template #prefix>
        <Icon icon="ep:search" />
      </template>
    </ns-input>
  </div>
  <div class="head-container">
    <el-tree
      ref="treeRef"
      :data="deptList"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :props="defaultProps"
      default-expand-all
      highlight-current
      node-key="id"
      @node-click="handleNodeClick"
    />
  </div>
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
import { defaultProps } from '@/utils/tree'

import { getDataSourcePage } from '@/api/assetList/index'

const deptName = ref('')
const deptList = ref<Tree[]>([]) // 树形结构
const treeRef = ref<InstanceType<typeof ElTree>>()
const curKey = ref<undefined | string>(undefined)

/** 获得部门树 */
const getTree = async () => {
  const { data } = await getDataSourcePage({
    datasourceType: '2',
    page: 1,
    pageSize: 9999
  })

  deptList.value = data.map((item) => ({
    name: item.name,
    id: item.id,
    children: []
  }))
  //默认选中第一个
  handleNodeClick({
    id: deptList.value[0].id
  })

  nextTick(() => {
    treeRef.value?.setCurrentKey(deptList.value[0].id)
  })
}

/** 基于名字过滤 */
const filterNode = (name: string, data: Tree) => {
  if (!name) return true
  return data.name.includes(name)
}

/** 处理部门被点击 */
const handleNodeClick = async (row: { [key: string]: any }) => {
  // if (curKey.value === row.id) {
  //   console.log('取消选择', row, curKey.value)
  //   treeRef.value?.setCurrentKey(undefined)
  //   curKey.value = undefined
  // }
  curKey.value = row.id
  emits('node-click', row)
}
const emits = defineEmits(['node-click'])

/** 监听deptName */
watch(deptName, (val) => {
  treeRef.value!.filter(val)
})

/** 初始化 */
onMounted(async () => {
  await getTree()
})
</script>
